<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/20 0020
 * Time: 22:58
 */

namespace Lib\Core;

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;

class Http
{
    /**
     * @var: Http_server服务端
     */
    protected $server;

    /**
     * @description:启动服务
     * @auth:yfl
     * @email:554665488@qq.com
     */
    public function run()
    {
        $config = Config::getInstance();
        $config->load();//载入配置文件

        $httpSet = $config->get('http');
        $this->server = new Server($httpSet['host'], $httpSet['port']);
        $this->server->set($httpSet['swoole_setting']);
        $this->server->on('request', [$this, 'request']);
        $this->server->on('Start', [$this, 'start']);
        $this->server->on('workerStart', [$this, 'workerStart']);

        //tcp服务端口监听
        if ((int)$httpSet['tcpable'] === 1) {
            $tcp = $config->get('tcp');
            $this->registerTcp($tcp);
        }

        $this->server->start();
    }

    public function registerTcp($tcp)
    {
//        $rpc=new Rpc();
//        $rpc->listen($this->server,$tcp);
    }

    public function request(Request $request, Response $response)
    {
        try {

            Route::getInstance()->dispatch($request, $response);

        } catch (\Exception $exception) {

            var_dump($exception->getMessage());
        }
    }

    public function start(\Swoole\Server $server)
    {
        $reload = Reload::getInstance();
        $reload->watch = [CONFIG_PATH, FRAME_PATH, APP_PATH];
        $reload->md5Flag = $reload->getMd5();
        swoole_timer_tick(3000, function () use ($reload) {
            if ($reload->reload()) {
                $this->server->reload(); //重启
            }
        });
    }

    public function workerStart($server, $worker_id)
    {
        //支持热加载
        $config = Config::getInstance();
        $config->loadLazy();
        //连接redis、连接数据库

        //加载路由配置文件
        include_once APP_PATH . '/route.php';
    }
}